package com.tc.dispatch.web.controller;

import java.util.*;
import java.io.*;
import javax.ejb.*;
import javax.servlet.*;
import javax.servlet.http.*;

import com.tc.dispatch.web.util.*;
import com.tc.dispatch.web.exception.*;

import com.tc.dispatch.aa.exception.*;
import com.tc.dispatch.aa.model.*;
import com.tc.dispatch.aa.ejb.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: ZJU</p>
 * @author DxFeng
 * @version 1.0
 */

public class UserState {
  private String user_id = null; // Identity
  

  private AA_DPServiceLocal aasl = null; // Business EJB handle
  private Map cache = new HashMap(); // Cache Permission Entries

  // Constructor, get the EJB Object handle.
  public UserState() {
    ServiceLocator sl = ServiceLocator.getInstance();
    try {
      aasl = ( (AA_DPServiceLocalHome) sl.getEJBLocalHome(JNDINames.
          AA_DPService_EJB_LOCAL)).create();
    }
    catch (CreateException ce) {
      throw new WEBSysException("CreateException found.", ce);
    }
  }

  public String getUserId() {
    return this.user_id;
  }

  // User for judging if the client logged in, if not, please login
  public boolean isLoggedIn() {
    return this.user_id != null;
  }

  // Login. only only when the client has no identity
  public boolean login(String user_id, String password) throws ServletException {
    // WEBSysException.assertTrue(this.user_id == null, "���Ѿ���½��");
    //System.out.println(user_id+"&&"+password);
    //System.out.println(this.user_id);
    if (this.user_id != null) {
      throw new WEBException(WEBException.ALREADY_LOGGED_IN);
    }

    boolean ret = false;
    try {
      ret = aasl.checkUserIdAndPassword(user_id, password);
      //System.out.println("ret:"+ret);
      if (ret) {
        this.user_id = user_id;
      }
      else {
        this.user_id = null;
      }
    }
    catch (AAException aae) {
      throw new ServletException(aae);
    }
    return ret;
  }

  // Check permission, used before accessing resources or functions
  public boolean checkPermission(String resource_id, String action_id) throws
      ServletException {
    //WEBSysException.assertTrue(this.user_id != null, "�㻹δ��½");
	  if(this.user_id==null)
		  return false;
    boolean ret;
    try {
      // ���Ȳ��� Cache ����û�У�ʹ�� resource_id + " && " + action_id ��Ϊ Key
      String key = resource_id + " && " + action_id;
      if (cache.containsKey(key)) {
        ret = ( (Boolean) cache.get(key)).booleanValue();
      }
      else {
        ret = aasl.checkUserPermission(this.user_id, resource_id, action_id);
        cache.put(key, new Boolean(ret));
      }
    }
    catch (AAException aae) {
      throw new ServletException(aae);
    }
    return ret;
  }

}
